<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/29
 * Time: 15:06
 */

namespace App\CronTask;

use App\Enums\SysKeyEnums;
use App\Enums\UrlEnums;
use EasySwoole\EasySwoole\Crontab\AbstractCronTask;
use EasySwoole\HttpClient\HttpClient;
use EasySwoole\MysqliPool\Mysql;

class TeamPointsCron extends AbstractCronTask
{
    //13排行榜
    //GET http://api.xxe.io/?resource=rank&func=team&event_id=
    public static function getRule(): string
    {
        // TODO: Implement getRule() method.
        return '@daily';
    }

    public static function getTaskName(): string
    {
        // TODO: Implement getTaskName() method.
        // 定时任务名称
        return 'taskThree';
    }
    static function run(\swoole_server $server, int $taskId, int $fromWorkerId,$flags=null)
    {
        $db = Mysql::defer('mysql');
        $events = $db->get('sc_event');
        foreach ( $events as $event ){
            $option = [
                'timestamp' => time(),
                'resource'  => 'rank',
                'func'      => 'team',
                'event_id'  => $event['event_id']
            ];
            $queries = [
                'app_key'   => SysKeyEnums::APP_KEY,
                'app_secret'=> SysKeyEnums::APP_SECRET,
            ];
            $queries = array_merge($queries,$option);
            ksort($queries);
            $sign = '';
            foreach ( $queries as $k=>$v ){
                if( $v ){
                    $sign .= $k."={$v}&";
                }
            }
            if( $sign ){
                $sign = substr($sign, 0, -1);
            }
            $url = UrlEnums::XXEURL.'?'.$sign.'&sign='.strtolower(md5($sign));
            $client = new HttpClient($url);
            $response = $client->get();
            $content = $response->getBody();
            $content = json_decode($content, true);
            if( !isset($content['data']) || empty($content['data']) ){
                continue;
            }
            $data = $content['data'];
            foreach ( $data as $k=>$v ){
                $res = $db->where('event_id',$event['event_id'])
                    ->where('country',$v['country'])
                    ->where('team_name',$v['team_name'])
                    ->getOne('sc_team_points');
                if( $res ){
                    $r = $db->where('id',$res['id'])->update('sc_team_points',[
                        'points' => $v['points'],
                        'rank'   => $v['rank']
                    ]);
                }else{
                    $r = $db->insert('sc_team_points',[
                        'event_id' => $event['event_id'],
                        'team_name' => $v['team_name'],
                        'country'   => $v['country'],
                        'points' => $v['points'],
                        'rank'   => $v['rank']
                    ]);
                }
            }
        }
    }
}